//
//  FirstMainViewController.m
//  Project_B
//
//  Created by 张闯的mac pro on 15/11/23.
//  Copyright © 2015年 张闯. All rights reserved.
//

#import "FirstMainViewController.h"
#import "AFNetworkHandler.h"
#import "FirstModel.h"
#import "FirstMainTableViewCell.h"
#import "FirstOtherTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "FirstTopViewViewController.h"
#import "FirstColumnViewController.h"
#import "MJRefresh.h"
#import "FirstSpecialTableViewCell.h"
#import "FirstSpecialViewController.h"
#import "MBProgressHUD.h"
#import "RESideMenu.h"
#import "FirstSearchViewController.h"
#import "AppDelegate.h"
#import "ZYAnimationLayer.h"
#import "UIImage+GIF.h"
#import "HeadCollectionViewCell.h"
#import <LocalAuthentication/LocalAuthentication.h>


@interface FirstMainViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *tableDataArr;
@property (nonatomic, strong) NSMutableArray *topViewArr;
@property (nonatomic, strong) UIPageControl *page;
@property (nonatomic, strong) UITableView *otherTableView;
@property (nonatomic, strong) NSMutableArray *otherTableDataArr;
@property (nonatomic, assign) NSInteger i;

@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) UISegmentedControl *seg;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIButton *button;

@end

@implementation FirstMainViewController


- (void)dealloc
{
    return;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createBeginView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.view.alpha = 1;
        self.navigationController.navigationBarHidden = NO;
        self.tabBarController.tabBar.hidden = NO;
        [self authenticateUser];
        [self initNavigationView];
        [self initGroup];
    });
}

- (void)createClickToTop
{
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button.frame = CGRectMake(330, 500, 30, 30);
    self.button.backgroundColor = [UIColor colorWithRed:60.0 / 255 green:149.0 / 255 blue:58.0 / 255 alpha:1];
    self.button.layer.cornerRadius = 5;
    [self.button setBackgroundImage:[UIImage imageNamed:@"top"] forState:0];
    [self.button addTarget:self action:@selector(topAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)topAction
{
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}


- (void)initGroup
{
    [self initArrays];
    //获取tableView数据
    [self getHeadData];
    [self getFirstMainTableData];
    [self getFirstOtherTableData];
//
//    //创建tableView
    [self createFirstMainTableView];
    [self createFirstOtherTableView];
    [self createHeadCollectionView];
    [self createClickToTop];
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:NO];
    self.hud.animationType = MBProgressHUDAnimationFade;
    self.i = 1;
    //下拉刷新
    MJRefreshGifHeader *head = [[MJRefreshGifHeader alloc] init];
    __weak typeof(self)weakSelf = self;
    head = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf getFirstMainTableData];
        } else {
            NSLog(@"");
        }
    }];
    NSString *name = @"gif1.gif";
    NSString *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImage *image = [UIImage sd_animatedGIFWithData:imageData];
    [head setImages:@[image] duration:1 forState:2];
    self.tableView.mj_header = head;
    
    //shang拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
       __strong typeof(self) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf getFootData];
        } else {
            NSLog(@"weakSelf");
        }
    }];
}

- (void)initArrays
{
    self.tableDataArr = [NSMutableArray array];
    self.topViewArr = [NSMutableArray array];
    self.otherTableDataArr = [NSMutableArray array];
}

- (void)initNavigationView
{
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"精选", @"专栏"]];
    self.seg.selectedSegmentIndex = 0;
    self.seg.tintColor = [UIColor whiteColor];
    self.seg.frame = CGRectMake(0, 0, 100, 30);
    [self.seg addTarget:self action:@selector(changeTableView:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = self.seg;
    //左侧按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-category"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    //右侧搜索按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo"] style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonAction)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
}

- (void)changeTableView:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0) {
        [UIView animateWithDuration:0.3 animations:^{
            self.tableView.frame = CGRectMake(0, 0, 375, 667 - 64);
            self.otherTableView.frame = CGRectMake(375, 0, 375, 667 - 64);
        }];
        
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            self.otherTableView.frame = CGRectMake(0, 0, 375, 667 - 64);
            self.tableView.frame = CGRectMake(-375, 0, 375, 667 - 64);
        }];
    }
}
#pragma mark - 第一个tableView

- (void)getFirstMainTableData
{
    NSString *str = @"http://api.lis99.com/v2/club/omnibusList/0/";
    [self loadDataForType:1 withURL:str];
}

- (void)getFootData
{
    NSString *str = [NSString stringWithFormat:@"http://api.lis99.com/v2/club/omnibusList/%ld/", self.i++];
    [self loadDataForType:2 withURL:str];
}

- (void)loadDataForType:(int)type withURL:(NSString *)urlString
{
    [AFNetworkHandler getUrl:urlString cookie:nil result:^(id result) {
        NSMutableArray *arr = [FirstModel transformWithArray:result[@"data"][@"omnibuslist"]];
        if (type == 1) {
            self.tableDataArr = arr;
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
            [self.view addSubview:self.tableView];
            [self.hud removeFromSuperview];
        } else if (type == 2) {
            [self.tableDataArr addObjectsFromArray:arr];
            [self.tableView reloadData];
            
//            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
//            
//            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationTop];
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:???? inSection:0];
//            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)getHeadData
{
    [AFNetworkHandler getUrl:@"http://api.lis99.com/v3/club/index/?user_id=(null)?" cookie:nil result:^(id result) {
        
        self.topViewArr = [FirstModel transformWithArray:result[@"data"][@"banners"]];
        [self.collectionView reloadData];
        [self.collectionView setContentOffset:CGPointMake(WIDTH * 100, 0)];

    }];
}
- (void)createHeadCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(375, 170);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 375, 170) collectionViewLayout:layout];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[HeadCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    
    [self.tableView.tableHeaderView addSubview:self.collectionView];
    //页码控制器
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake((375 - 90) / 2, self.tableView.tableHeaderView.frame.size.height - 70, 100, 30)];
    self.page.numberOfPages = 4;
    self.page.currentPageIndicatorTintColor = [UIColor redColor];
    [self.tableView.tableHeaderView addSubview:self.page];
}

- (void)createFirstMainTableView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 205)];
    headerView.tag = 1002;
    
    UILabel *colorLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 175, 10, 30)];
    colorLabel.backgroundColor = [UIColor colorWithRed:60.0 / 255 green:149.0 / 255 blue:58.0 / 255 alpha:1];
    [headerView addSubview:colorLabel];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(33, 175, 150, 30)];
    titleLabel.text = @"精彩游记和专题";
    titleLabel.textColor = [UIColor lightGrayColor];
    [headerView addSubview:titleLabel];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 375, 667 - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = headerView;
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(changeToOtherView)];
    swipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.tableView addGestureRecognizer:swipe];
    
    [self.tableView registerClass:[FirstMainTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[FirstSpecialTableViewCell class] forCellReuseIdentifier:@"special"];
}

- (void)changeToOtherView
{
    [UIView animateWithDuration:0.3 animations:^{
        
        self.seg.selectedSegmentIndex = 1;
        self.otherTableView.frame = CGRectMake(0, 0, 375, 667 - 44 - 64);
        self.tableView.frame = CGRectMake(-375, 0, 375, 667 - 44);
    }];
}

#pragma mark - 第二个tableView
- (void)getFirstOtherTableData
{
    [AFNetworkHandler getUrl:@"http://api.lis99.com/v3/club/taglist/0/" cookie:nil result:^(id result) {
        NSArray *arr = result[@"data"][@"taglist"];
        self.otherTableDataArr = [FirstModel transformWithArray:arr];

        [self.otherTableView reloadData];
    }];
}

- (void)createFirstOtherTableView
{
    self.otherTableView = [[UITableView alloc] initWithFrame:CGRectMake(375, 0, 375, 667 - 44 - 64) style:UITableViewStylePlain];
    self.otherTableView.tag = 1001;
    [self.view addSubview:self.otherTableView];
    self.otherTableView.delegate = self;
    self.otherTableView.dataSource = self;
    self.otherTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(changeToMainView)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.otherTableView addGestureRecognizer:swipe];
    
    [self.otherTableView registerClass:[FirstOtherTableViewCell class] forCellReuseIdentifier:@"otherCell"];
}

- (void)changeToMainView
{
    [UIView animateWithDuration:0.3 animations:^{
        
        self.seg.selectedSegmentIndex = 0;
        self.tableView.frame = CGRectMake(0, 0, 375, 667 - 44);
        self.otherTableView.frame = CGRectMake(375, 0, 375, 667 - 44 - 64);
    }];
}

#pragma mark - tableView 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 1001) {
        return self.otherTableDataArr.count;
    } else {
        return self.tableDataArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 1001) {
        FirstOtherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"otherCell"];
        cell.otherFirstModel = self.otherTableDataArr[indexPath.row];
        return cell;
        
    } else if ([((FirstModel *)self.tableDataArr[indexPath.row]).type isEqualToString:@"4"]){
        
        FirstSpecialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"special"];
        cell.specialModel = self.tableDataArr[indexPath.row];
        return cell;
        
    } else {
        
        FirstMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.firstModel = self.tableDataArr[indexPath.item];
//        cell.textLabel.text = @"1";
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (tableView.tag == 1001) {
        FirstColumnViewController *ColumnVC = [[FirstColumnViewController alloc] init];
        
        ColumnVC.idString = [self.otherTableDataArr[indexPath.row] first_id];
        [self.navigationController pushViewController:ColumnVC animated:YES];
        
    } else {
        FirstTopViewViewController *topVC = [[FirstTopViewViewController alloc] init];
        topVC.idString = [self.tableDataArr[indexPath.row] topic_id];
        topVC.typeStr = ((FirstModel *)self.tableDataArr[indexPath.row]).type;
        
        if ([topVC.typeStr isEqualToString:@"4"]) {
            
            NSLog(@"4");
            NSLog(@"%@", self.tableDataArr[indexPath.row]);
            FirstSpecialViewController *specialVC = [[FirstSpecialViewController alloc] init];
            specialVC.idString = [self.tableDataArr[indexPath.row] first_id];
            [self.navigationController pushViewController:specialVC animated:YES];
            
        } else {
            [self.navigationController pushViewController:topVC animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}


#pragma mark - collectionView delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 300;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.topViewArr.count - 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HeadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    cell.model = self.topViewArr[indexPath.item];
    self.page.currentPage = indexPath.item;
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld", indexPath.item);
    FirstTopViewViewController *topVC = [[FirstTopViewViewController alloc] init];
    topVC.typeStr = [self.topViewArr[indexPath.item] category];
    topVC.idString = [self.topViewArr[indexPath.item] contents];
    [self.navigationController pushViewController:topVC animated:YES];
    
}

#pragma mark - scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableView) {
        if (self.tableView.contentOffset.y > 1000) {
            [self.view addSubview:self.button];
        } else {
            [self.button removeFromSuperview];
        }
    }
}

- (void)rightButtonAction
{
    FirstSearchViewController *searchVC = [[FirstSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
#pragma mark - 启动页
- (void)createBeginView
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    [imageView setImage:[UIImage imageNamed:@"back"]];
    [self.view addSubview:imageView];
    
    UIView *view = [[UIView alloc] initWithFrame:imageView.frame];
    view.alpha = 0.8;
    view.backgroundColor = [UIColor blackColor];
    [imageView addSubview:view];
    
    ZYAnimationLayer *layer = [[ZYAnimationLayer alloc] init];
    UIView *layerView = [[UIView alloc] initWithFrame:CGRectMake(35, 350, 200, 100)];
    [self.view addSubview:layerView];
    layerView.backgroundColor = [UIColor clearColor];
    
    [layer createAnimationLayerWithString:@"LTZ户外" andRect: CGRectMake(0, -200.0f, CGRectGetWidth(self.view.layer.bounds) - 40.0f, CGRectGetHeight(self.view.layer.bounds) - 84.0f) andView:layerView andFont:[UIFont boldSystemFontOfSize:40] andStrokeColor:[UIColor whiteColor]];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:3 animations:^{
            view.alpha = 0.4;
            layerView.frame = CGRectMake(35, 200, 200, 100);
            imageView.transform = CGAffineTransformScale(imageView.transform, 1.1, 1.1);
            
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:2 animations:^{
                imageView.alpha = 0;
                layerView.alpha = 0;
            } completion:^(BOOL finished) {
                [layer removeFromSuperlayer];
                [imageView removeFromSuperview];
                [layerView removeFromSuperview];
                [view removeFromSuperview];
            }];
        }];
    });
}

- (void)authenticateUser
{
    //初始化上下文对象
    LAContext* context = [[LAContext alloc] init];
    //错误对象
    NSError* error = nil;
    NSString* result = @"三哥需要自己的指纹";
    
    //首先使用canEvaluatePolicy 判断设备支持状态
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        //支持指纹验证
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
            if (success) {
                //验证成功，主线程处理UI
                NSLog(@"成功");
                NSLog(@"%@", context);
            }
            else
            {
                NSLog(@"%@",error.localizedDescription);
                switch (error.code) {
                    case LAErrorUserFallback:
                    {
                        NSLog(@"llll");
                        //切换到其他APP，系统取消验证Touch ID
                        [self alertAction:@"没有密码的,哈哈~~防窥探专用"];
                        break;
                    }
                    case LAErrorPasscodeNotSet:
                    {
                        NSLog(@"ll213434ll");
                        //切换到其他APP，系统取消验证Touch ID
                        [self alertAction:@"防窥探专用~~哈哈哈~~木马~~"];
                        break;
                    }
                    case LAErrorUserCancel:
                    {
                        NSLog(@"Authentication was cancelled by the user");
                        NSLog(@"没有权限,程序退出");

                        [self alertAction:@"防窥探专用~~哈哈哈~~木马~~"];
                        
                        //用户取消验证Touch ID
                        break;
                    }
                    case LAErrorAuthenticationFailed:
                    {
                        NSLog(@"User selected to enter custom password");
                        [self alertAction:@"防窥探专用~~哈哈哈~~木马~~"];
                        break;
                    }
                    default:
                    {
                        [self alertAction:@"防窥探专用~~哈哈哈~~木马~~"];
                        break;
                    }
                }
            }
        }];
    }
    else
    {
        //不支持指纹识别，LOG出错误详情
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:
            {
                NSLog(@"TouchID is not enrolled");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                NSLog(@"A passcode has not been set");
                break;
            }
            default:
            {
                NSLog(@"TouchID not available");
                break;
            }
        }
        NSLog(@"%@",error.localizedDescription);
    }  
}

- (void)alertAction:(NSString *)string
{
    UIAlertController *alertContrl = [UIAlertController alertControllerWithTitle:@"看仔细" message:string preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertContrl animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
